package edu.ycu.aladdin.common;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 基本公共配置.
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @since 1.0
 */
public class CommonConfig {

    public static RedisTemplate<String, String> redisTemplateWithStringSerializer(RedisTemplate redisTemplate) {
        // 设置序列化方式.
        RedisSerializer stringSerializer = new StringRedisSerializer();
        setSerializer(stringSerializer, redisTemplate);
        return redisTemplate;
    }

    public static RedisTemplate<Object, Object> redisTemplateWithJSONSerializer(RedisTemplate redisTemplate) {

        RedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        setSerializer(fastJsonRedisSerializer, redisTemplate);
        return redisTemplate;
    }

    public static RedisTemplate<String, Object> redisTemplateWithBasicSerializer(RedisTemplate redisTemplate) {

        RedisSerializer stringSerializer = new StringRedisSerializer();
        RedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(fastJsonRedisSerializer);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        return redisTemplate;
    }

    private static void setSerializer(RedisSerializer serializer, RedisTemplate redisTemplate) {
        redisTemplate.setKeySerializer(serializer);
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashKeySerializer(serializer);
        redisTemplate.setHashValueSerializer(serializer);
    }
}
